import {
  Text,
  View,
  ScrollView,
  Image,
  TouchableOpacity,
  StyleSheet,
} from "react-native";
import PageContainer from "@/components/PageContainer";
import React, { useEffect, useState } from "react";
import { LinearGradient } from "expo-linear-gradient";
import { useRouter ,useLocalSearchParams} from "expo-router"; // 引入 useRouter
import QRCode from "react-native-qrcode-svg";
import { copyToClipboard } from "@/uitls/common";
import SelectionModal from "@/components/SelectionModal";
import {
  findAllSimpleAssetsFnApi,
  findAssetChainNetInfoFnAPi,
  getAssetCoinDepositAddressFnApi,
} from "./api";
import { useTranslation } from "react-i18next";

import { ToastAPI } from "@/components/Toast";
export default function Recharge() {
  const { t } = useTranslation();
const params = useLocalSearchParams<{ 
  assetId: string,symbol:string
  }>();
  const [currencyModalVisible, setCurrencyModalVisible] = useState(false);
  const [networkModalVisible, setNetworkModalVisible] = useState(false);
  const router = useRouter(); // 获取路由对象
  const [currencyList, setCurrencyList] = useState([]);
  const [currencyItemInfo, setCurrencyItemInfo] = useState<any>(null);
  const [networkList, setNetworkList] = useState([]);
  const [networkItemInfo, setNetworkItemInfo] = useState<any>(null);
  const [qrCode, setQrCode] = useState("");
  const getCurrencyList = async () => {
    const res: any = await findAllSimpleAssetsFnApi();
    setCurrencyList(res.result);
  };
  useEffect(() => {
    getCurrencyList();
    if(params?.assetId){
      initData({id:params?.assetId,symbol:params?.symbol})
    }
  }, []);
  
  const initData = async (item:any) => {
    setCurrencyItemInfo(item);
    setCurrencyModalVisible(false);
    setNetworkItemInfo(null);
    ToastAPI.loading(t("common.loading"));
    setQrCode("");
    //调用接口请求网卡
    try {
      const res: any = await findAssetChainNetInfoFnAPi({
        assetId: item.id,
      });
      ToastAPI.close();
      if (res.code === 0) {
        setNetworkList(res.result);
      } else {
        ToastAPI.error(res?.errMsg);
      }
    } catch (error) {
      ToastAPI.close();
      // 捕获错误并关闭加载提示
      ToastAPI.error(JSON.stringify(error) || t("auth.request_error"));
    } 
  }
  return (
    <PageContainer>
      <View className="bg-[#000] flex-1 p-[13px]">
        <View className="items-center flex-row h-[46px]">
          <TouchableOpacity onPress={() => router.back()}>
            <Image
              source={require("@/assets/images/return-left.png")}
              className="w-[18px] h-[18px]"
            />
          </TouchableOpacity>
          <View className="flex-1 flex-row justify-center">
            <Text className="text-[#fff] text-[18px]">
              {t("rechargex.recharge")}
            </Text>
          </View>
          <TouchableOpacity
            onPress={() => router.push("/recharge/rechargeHistorical")}
          >
            <Image
              source={require("@/assets/images/jl.png")}
              className="w-[18px] h-[18px]"
            />
          </TouchableOpacity>
        </View>
        <ScrollView
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          style={{ flex: 1 }}
        >
          <View className="mt-[22px]">
            <Text className="text-[#D7D7D7] text-[16px]">
              {t("rechargex.currency")}
            </Text>
            <TouchableOpacity onPress={() => setCurrencyModalVisible(true)}>
              <View
                style={styles.input}
                className="flex-row justify-between gap-[10px]"
              >
                <Text
                  className="flex-1 text-[14px] leading-[50px]"
                  style={{ color: !currencyItemInfo ? "#949494" : "#fff" }}
                >
                  {!currencyItemInfo
                    ? t("rechargex.select_currency")
                    : currencyItemInfo.symbol}
                </Text>
                <Text className="text-[rgb(83,192,255)] text-[14px] leading-[50px]">
                  {t("rechargex.switch_currency")}
                </Text>
              </View>
            </TouchableOpacity>
          </View>
          <View className="mt-[22px]">
            <Text className="text-[#D7D7D7] text-[16px]">
              {t("rechargex.network")}
            </Text>
            <TouchableOpacity
              onPress={() => {
                setNetworkModalVisible(true);
              }}
            >
              <View style={styles.input} className="flex-row justify-between">
                <Text
                  className="flex-1 text-[14px] leading-[50px]"
                  style={{ color: !networkItemInfo ? "#949494" : "#fff" }}
                >
                  {!networkItemInfo
                    ? t("rechargex.select_network")
                    : networkItemInfo.chainFullName}
                </Text>
                <Text className="text-[rgb(83,192,255)] text-[14px] leading-[50px]">
                  {t("rechargex.select_network")}
                </Text>
              </View>
            </TouchableOpacity>
          </View>
          {qrCode && (
            <View style={styles.roundedBorderView}>
              <View className="flex-row w-full justify-center">
                <View className="bg-[#fff] p-[13px]">
                  <QRCode
                    value={qrCode}
                    size={215}
                    color="black"
                    backgroundColor="white"
                  />
                </View>
              </View>
              <Text className="text-[#FDEAC1] text-[14px] text-center">
                — {t("rechargex.address")} —
              </Text>
              <Text className="text-[#898B81] text-[14px]">{qrCode}</Text>
              <TouchableOpacity onPress={() => copyToClipboard(qrCode)}>
                <LinearGradient
                  style={styles.bbtn}
                  colors={["#F4DDC3", "#E6B79A"]}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 0 }}
                >
                  <Text className="text-[#1F110F] text-[16px] font-bold">
                    {t("rechargex.copy_address")}
                  </Text>
                </LinearGradient>
              </TouchableOpacity>
            </View>
          )}

          <View className="mt-[13px]">
            <Text className="text-[#fff] text-[18px] font-bold">
              {t("rechargex.recharge_instructions")}
            </Text>
            <Text className="text-[#949494] text-[14px] mt-[5px]">
              {t("rechargex.do_not_recharge_elsewhere")}
            </Text>
            <Text className="text-[#949494] text-[14px] mt-[5px]">
              {t("rechargex.ensure_network_normal")}
            </Text>
            <Text className="text-[#949494] text-[14px] mt-[5px]">
              {t("rechargex.system_update")}
            </Text>
            <Text className="text-[#949494] text-[14px] mt-[5px]">
              {t("rechargex.minimum_recharge")}
            </Text>
          </View>
        </ScrollView>
      </View>
      <SelectionModal
        visible={currencyModalVisible}
        title={t("rechargex.select_currency")}
        listData={currencyList}
        renderKey="name"
        onClose={() => setCurrencyModalVisible(false)}
        onSelect={async (item) => {
          initData(item)
        }}
        renderItem={(item) => (
          <View className="flex-1 flex-row gap-[10px] justify-between items-center">
            <View className="flex-row gap-[10px] items-center flex-1">
              <Image
                source={{ uri: item.logo }}
                className="w-[20px] h-[20px] rounded-full"
              />
              <Text className="text-[16px] text-[#fff]">{item.symbol}</Text>
              <Text className="text-[16px] text-[#949494]">
                {item.fullName}
              </Text>
            </View>
            {item.depositStatus === 1 && (
              <Text className="text-[red] text-[14px]">暂停</Text>
            )}
          </View>
        )}
      />
      <SelectionModal
        visible={networkModalVisible}
        title={t("rechargex.select_network")}
        listData={networkList}
        renderKey="name"
        onClose={() => setNetworkModalVisible(false)}
        onSelect={async (item) => {
          setQrCode("");
          setNetworkItemInfo(item);
          setNetworkModalVisible(false);
          ToastAPI.loading(t("common.loading"));
          //调用接口请求网卡
          setTimeout(async () => {
            try {
              const res: any = await getAssetCoinDepositAddressFnApi({
                coinId: item.coinId,
              });
              ToastAPI.close();
              if (res.code === 0) {
                setQrCode(res.result);
              } else {
                ToastAPI.error(res?.errMsg);
              }
            } catch (error) {
              ToastAPI.close();
              // 捕获错误并关闭加载提示
              ToastAPI.error(JSON.stringify(error) || t("auth.request_error"));
            }
          }, 1000);
        }}
        renderItem={(item) => (
          <View className="flex-1">
            <View className="flex-row justify-between gap-[10px] items-center">
              <Text className="text-[#fff] text-[16px]">{item.coinSymbol}</Text>
              <Text className="text-[#fff] text-[16px]">
                =={t("rechargex.minute")}
              </Text>
            </View>
            <View className="flex-row justify-between gap-[10px] items-center">
              <Text className="text-[#949494] text-[14px]">
                {item.chainFullName}
              </Text>
              <Text className="text-[#949494] text-[14px]">
                15{t("rechargex.second")}
              </Text>
            </View>
          </View>
        )}
      />
    </PageContainer>
  );
}

const styles = StyleSheet.create({
  input: {
    backgroundColor: "#25262A",
    borderRadius: 10,
    marginTop: 15,
    height: 50,
    paddingHorizontal: 12,
  },

  bbtn: {
    height: 50,
    borderRadius: 30,
    justifyContent: "center",
    alignItems: "center",
    width: "100%",
  },
  roundedBorderView: {
    borderWidth: 1,
    borderColor: "#979797",
    borderRadius: 10,
    padding: 25,
    marginTop: 22,
    flexDirection: "column",
    gap: 10,
  },
});
